<template>
  <div class="updateAvatar">
    <img ref="image" :src="img" class="image" />

    <van-nav-bar
      left-text="取消"
      right-text="完成"
      @click-left="$emit('colose-avatar')"
      @click-right="onSubmit"
    />
  </div>
</template>
<script>
import { setUserAvatar } from '@/api/user'
import { Toast } from 'vant'
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
export default {
  name: 'UpdateAvatar',
  data () {
    return {
      img: window.URL.createObjectURL(this.file),
      cropper: null
    }
  },
  created () {},
  methods: {
    async onSubmit () {
      Toast.loading({
        message: '保存中...',
        forbidClick: true
      })
      const file = await this.getCroppedCanvas()
      console.log(file)
      const arr = file.type.split('/')
      const avatarname = `${this.username}.${arr[1]}`
      const fd = new FormData()
      fd.append('image', file, avatarname)
      try {
        await setUserAvatar(fd)
        this.$emit('colose-avatar')
        Toast.success('保存成功')
        this.$emit('update-avatar', window.URL.createObjectURL(file))
      } catch (error) {
        Toast.fail('修改失败,头像大小为8M的jpg、png图片')
        return error
      }
    },
    // 获取裁切后的图像
    getCroppedCanvas () {
      return new Promise((resolve) => {
        this.cropper.getCroppedCanvas().toBlob((blob) => {
          resolve(blob)
        })
      })
    }
  },
  components: {},
  props: {
    file: {
      // type: Object,
      required: true
    },
    username: {
      type: String,
      required: true
    }
  },
  watch: {},
  computed: {},
  mounted () {
    const image = this.$refs.image
    this.cropper = new Cropper(image, {
      aspectRatio: 1,
      viewMode: 1,
      dragMode: 'none',
      responsive: false,
      restore: false,
      cropBoxResizable: false,
      minContainerHeight: 500
    })
  }
}
</script>

<style lang="less" scoped>
.updateAvatar {
  /deep/.van-nav-bar {
    background-color: white;
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
  }
  .image {
    display: block;
    max-width: 100%;
  }
  /deep/.cropper-container {
    margin-top: 46px;
  }
}
</style>
